package com.qfedu.edu.slot.impl;

import com.qfedu.edu.exception.handler.BusinessException;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.slot.base.SlotChain;
import com.qfedu.edu.slot.generate.GenerateSlot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

@Component
public class SlotChainImpl implements SlotChain {
    //注入GenerateSlot对象
    @Autowired
    private List<GenerateSlot> slotList;
    //定义TreeSet容器，用于存放GenerateSlot对象
    private TreeSet<GenerateSlot> generateSlots=new TreeSet<>();

    @PostConstruct//资源初始化注解
    public void init(){
        for (int i = 0; i < slotList.size(); i++) {
            //将GenerateSlot对象加入TreeSet集合
            generateSlots.add(slotList.get(i));
        }
    }

    @Override
    public boolean dealReq(HttpServletRequest req) {
        //遍历TreeSet集合，依次调用GenerateSlot对象的dealReq方法，直到有一个GenerateSlot对象返回true
        Iterator<GenerateSlot> iterator = generateSlots.iterator();

        while (iterator.hasNext()){
            //获取下一个GenerateSlot对象
            GenerateSlot next = iterator.next();
            //调用dealReq方法,
            if (!next.dealReq(req)){
                //抛出业务异常
                throw new BusinessException(ResponseCode.SLOT_INVOKE_EXCEPTION.getCode(),ResponseCode.SLOT_INVOKE_EXCEPTION.getMsg());
            }
        }
        return true;
    }
}
